<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="缩略图" prop="thumbnail">
        <el-input
          v-model="queryParams.thumbnail"
          placeholder="请输入缩略图"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['business:matterManage:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:matterManage:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:matterManage:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['business:matterManage:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="matterManageList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="" align="center" prop="id" v-if="true" /> -->
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="缩略图" align="center" prop="thumbnail">
        <template #default="scope">
          <ImagePreview
            :width="100"
            :height="100"
            :src="scope.row.thumbnail"
            :preview-src-list="[scope.row.thumbnail]"
          />
        </template>
      </el-table-column>
      <el-table-column label="分享次数" align="center" prop="shareNum" />
      <el-table-column label="点击次数" align="center" prop="clickNum" />
      <el-table-column label="点击人数" align="center" prop="clickPersonNum" />
      <el-table-column label="预约人数" align="center" prop="subscribeNum" />
      <el-table-column label="预约率" align="center" prop="subscribeRate" />
      <el-table-column label="素材状态" align="center" prop="status">
        <template #default="scope">
          <el-tag
            :type="scope.row.status === '0' ? 'success' : 'danger'"
            disable-transitions
            >{{ scope.row.status === "0" ? "启用" : "停用" }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <div class="edit">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['business:matterManage:edit']"
              >修改</el-button
            >
            <el-button
              link
              type="primary"
              icon="View"
              @click="handleUpdate(scope.row, 'preview')"
              v-hasPermi="['business:matterManage:edit']"
              style="margin-left: 0; margin-top: 10rpx"
              >预览</el-button
            >
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['business:matterManage:remove']"
              style="margin-left: 0; margin-top: 10rpx"
              >删除</el-button
            >
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDetials(scope.row)"
              v-hasPermi="['business:matterManage:detials']"
              style="margin-left: 0; margin-top: 10rpx"
              >查看按钮数据</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改素材信息管理对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="800px"
      append-to-body
      @close="handleClose"
    >
      <div class="" v-if="isPreview">
        <div class="preview">
          <div class="miniprogram-head">
            <el-image
              style="width: 375px; height: 80px"
              src="https://geekhair.oss-cn-beijing.aliyuncs.com/2024/01/24/dc83e728c8b64706b86540f7dfa8e1bb.png"
            />

            <!-- <div class="time">{{ nowTime }}</div> -->
            <!-- <div class="head-title ellipsis">{{ title }}</div> -->
            <div class="miniprogram-con">
              <!-- <iframe :src="`${urlKey}`" /> -->
            </div>
          </div>

          <div class="erweima-wraper">
            <div v-for="item in attributeJsonList" :key="item.type">
              <el-image
                v-if="item.fileType === 'image'"
                style="width: 375px"
                :src="item.fileUrl"
                fit="contain"
              />
              <video
                v-if="item.fileType === 'video'"
                style="width: 375px"
                :src="item.fileUrl"
                :show-play-btn="false"
                controls
                :loop="false"
                :autoplay="false"
                class="video-thumbnail"
              />
            </div>
          </div>
        </div>
      </div>
      <el-form
        ref="matterManageRef"
        :model="form"
        :rules="rules"
        label-width="80px"
        v-else
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="缩略图" prop="thumbnail">
          <!-- <el-input v-model="form.thumbnail" placeholder="请输入缩略图" /> -->
          <image-uploads v-model="form.thumbnail" :limit="1"></image-uploads>
        </el-form-item>

        <!-- 添加素材图片和图片类型 -->
        <el-form-item label="" prop="attributeJson">
          <div
            class="el-form-item-content-add"
            v-for="(item, index) in attributeJsonList"
            :key="index"
          >
            <div style="display: flex">
              <div style="width: 105px">类型：</div>
              <el-select
                v-model="item.type"
                placeholder="请选择类型"
                @change="handleDelChange"
              >
                <el-option
                  v-for="dict in matter_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </div>
            <div style="display: flex; margin-top: 20px">
              <div style="width: 150px">添加外链地址：</div>
              <el-input
                v-model="item.linkUrl"
                type="text"
                placeholder="请输入外链地址"
              />
            </div>
            <div
              style="display: flex; margin-top: 20px"
              v-if="isDelType === '1' || item.type === '1'"
            >
              <div style="width: 105px">请上传视频：</div>
              <video-upload v-model="item.fileUrl"></video-upload>
            </div>

            <div style="display: flex; margin-top: 20px" v-else>
              <div style="width: 105px">请上传图片：</div>
              <image-uploads v-model="item.fileUrl" :limit="1"></image-uploads>
            </div>
            <div style="display: flex; margin-top: 20px">
              <el-button type="danger" @click="onDelImg(index)">删除</el-button>
              <el-button
                type="primary"
                @click="onAddBox(index)"
                v-if="item.isAddStatus"
              >
                新增
              </el-button>
            </div>
          </div>
          <!-- ----------------------------分割线--------------------------------------------------------------------------------------------- -->
          <div
            class="el-form-item-content-add"
            v-if="
              isAddStatus || (form.matterInfo && form.matterInfo.length === 0)
            "
          >
            <div style="display: flex">
              <div style="width: 105px">类型：</div>
              <el-select
                v-model="matterInfo.type"
                placeholder="请选择类型"
                @change="handleAddChange"
              >
                <el-option
                  v-for="dict in matter_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </div>

            <div style="display: flex; margin-top: 20px">
              <div style="width: 150px">添加外链地址：</div>
              <el-input
                v-model="matterInfo.linkUrl"
                type="text"
                placeholder="请输入外链地址"
              />
            </div>
            <div
              style="display: flex; margin-top: 20px"
              v-if="isAddType === '1'"
            >
              <div style="width: 105px">请上传视频：</div>
              <video-upload v-model="matterInfo.fileUrl"></video-upload>
            </div>

            <div style="display: flex; margin-top: 20px" v-else>
              <div style="width: 105px">请上传图片：</div>
              <image-uploads
                v-model="matterInfo.fileUrl"
                :limit="1"
              ></image-uploads>
            </div>
            <div style="display: flex; margin-top: 20px">
              <el-button type="primary" @click="onAddImg">保存</el-button>
              <el-button type="primary" @click="isAddStatus = true"
                >新增</el-button
              >
            </div>

            <!-- <text style="color: red">注：填完数据请点击新增</text> -->
          </div>
        </el-form-item>
        <el-form-item label="显示状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer" v-if="!isPreview">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      :title="title"
      v-model="openButtonData"
      width="800px"
      append-to-body
      @close="handleClose"
    >
      <el-table v-loading="loading" :data="matterButtonList">
        <el-table-column label="素材id" align="center" prop="matterId" />
        <el-table-column label="缩略图" align="center" prop="fileUrl">
          <template #default="scope">
            <ImagePreview
              :width="100"
              :src="scope.row.fileUrl"
              :preview-src-list="[scope.row.fileUrl]"
            />
          </template>
        </el-table-column>
        <!-- <el-table-column label="素材序列号" align="center" prop="matterSn" /> -->
        <el-table-column label="点击次数" align="center" prop="clickNum" />
        <el-table-column
          label="点击人数"
          align="center"
          prop="clickPersonNum"
        />
        <el-table-column label="预约人数" align="center" prop="subNum" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup name="MatterManage">
import {
  listMatterManage,
  getMatterManage,
  delMatterManage,
  addMatterManage,
  updateMatterManage,
  buttonDataListApi,
} from "@/api/business/matterManage";
//
const { proxy } = getCurrentInstance();
const { matter_type, sys_normal_disable } = proxy.useDict(
  "matter_type",
  "sys_normal_disable"
);

const matterManageList = ref([]);
const matterButtonList = ref([]);
const open = ref(false);
const openButtonData = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const isAddStatus = ref(true);
const attributeJsonList = ref([]);
const isDelType = ref(0);
let matterInfo = ref({
  type: "",
  fileUrl: "",
  linkUrl: "",
  isAddStatus: true,
});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: undefined,
    thumbnail: undefined,
    status: undefined,
  },
  rules: {
    id: [{ required: true, message: "不能为空", trigger: "blur" }],
    title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
    thumbnail: [{ required: true, message: "缩略图不能为空", trigger: "blur" }],
    status: [
      {
        required: true,
        message: "素材状态： 0 = 启用，2 = 停用不能为空",
        trigger: "change",
      },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

// 新增商品其他属性
function onAddImg() {
  isAddStatus.value = false;
  console.log("新增", matterInfo.value, isAddType.value);
  // matterInfo.value.isAddStatus = false;
  attributeJsonList.value.push(matterInfo.value);
  console.log(attributeJsonList.value);
  matterInfo.value = {
    type: "",
    fileUrl: "",
    linkUrl: "",
    isAddStatus: true,
  };
}
// 删除商品其他属性
function onDelImg(index) {
  attributeJsonList.value.splice(index, 1);
}
// 新增新的图片
function onAddBox(index) {
  console.log(index, attributeJsonList.value[index]);
  isAddStatus.value = true;
  attributeJsonList.value[index].isAddStatus = false;
}

const isAddType = ref(0);
// 选择类型
function handleAddChange(item) {
  console.log(item);
  isAddType.value = item;
}
function handleDelChange(item) {
  console.log(item);
  isDelType.value = item;
}

/** 查询素材信息管理列表 */
function getList() {
  loading.value = true;
  listMatterManage(queryParams.value).then((response) => {
    matterManageList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    title: null,
    thumbnail: null,
    status: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
  };
  attributeJsonList.value = [];
  proxy.resetForm("matterManageRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加素材信息管理";
}
const isPreview = ref(false);
/** 修改按钮操作 */
function handleUpdate(row, val) {
  if (val) {
    isPreview.value = true;
    title.value = "预览";
  } else {
    isPreview.value = false;
    title.value = "修改素材信息管理";
  }
  isAddStatus.value = false;
  loading.value = true;
  reset();
  const _id = row.id || ids.value;
  getMatterManage(_id).then((response) => {
    console.log(response.data);

    response.data.matterInfo.forEach((item) => {
      let arr = item.fileUrl.split(".");
      let type = arr[arr.length - 1];
      if (type === "jpg" || type === "png") {
        item.fileType = "image";
      } else {
        item.fileType = "video";
      }
    });

    attributeJsonList.value = response.data.matterInfo;
    matterInfo.value = {
      type: "",
      fileUrl: "",
      linkUrl: "",
      isAddStatus: true,
    };
    loading.value = false;
    form.value = response.data;
    open.value = true;
  });
}

// j监听弹框关闭
function handleClose() {
  isPreview.value = false;
  isAddStatus.value = true;
}

// 点击查看按钮详情
function handleDetials(row) {
  loading.value = true;
  const _id = row.id || ids.value;
  buttonDataListApi(_id).then((response) => {
    openButtonData.value = true;
    console.log(response.rows);
    matterButtonList.value = response.rows;
    loading.value = false;
  });
}

/** 提交按钮 */
function submitForm() {
  console.log(attributeJsonList.value, "00000000");
  let arr = [];
  attributeJsonList.value.forEach((item) => {
    if (item.type && item.fileUrl) arr.push(item);
  });
  console.log("arr=====>>>>", arr);
  form.value.matterInfo = arr;

  console.log(form.value);
  // return;
  proxy.$refs["matterManageRef"].validate((valid) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id != null) {
        updateMatterManage(form.value)
          .then((response) => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          })
          .finally(() => {
            buttonLoading.value = false;
          });
      } else {
        addMatterManage(form.value)
          .then((response) => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          })
          .finally(() => {
            buttonLoading.value = false;
          });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除素材信息管理编号为"' + _ids + '"的数据项？')
    .then(function () {
      loading.value = true;
      return delMatterManage(_ids);
    })
    .then(() => {
      loading.value = true;
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {})
    .finally(() => {
      loading.value = false;
    });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "business/matterManage/export",
    {
      ...queryParams.value,
    },
    `matterManage_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>
<style lang="scss" scoped>
.edit {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
.el-form-item-content-add {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin-bottom: 40px;
  width: 100%;
  background: #fafafa;
  padding: 20px;
  border-radius: 10px;
}
.preview {
  padding-top: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  max-width: 800px !important;
  background: #fafafa;

  .miniprogram-head {
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
  }
}
</style>
